import type { llmBaseProvider } from './baseProvider'
import type { LLMProviderConfig } from './type'
import $config from '@/config'

/**
 * LLM Provider 实现调用类
 */
class LLMProvider {
  // 缓存实例，key为provider name
  private static instanceCache: Map<
    string,
    { config: LLMProviderConfig; instance: llmBaseProvider }
  > = new Map()

  /**
   * 获取实现类
   *
   * @param id 提供商ID
   * @param config 配置项
   * @returns
   */
  public static instance = async (
    id: string,
    config: LLMProviderConfig,
  ): Promise<llmBaseProvider> => {
    const cached = LLMProvider.instanceCache.get(id)
    // 如果缓存存在且配置未变，直接返回
    if (cached && JSON.stringify(cached.config) === JSON.stringify(config)) {
      return cached.instance
    }
    // 基于配置项实例化
    const supplier = $config.llm.suppliers.find((item) => item.id === id)
    if (supplier) {
      const instance = new supplier.provider(config)
      // 更新缓存
      LLMProvider.instanceCache.set(id, { config, instance })
      return instance
    } else {
      throw new Error('LLM Provider init error: unknow llm supplier: ' + id)
    }
  }
}

export default LLMProvider
